"use strict";

// register communication port.
var port = chrome.extension.connect({
			name : "deliciousBookmark"
		});

var sendBookmark = function() {
	var responsePort = chrome.extension.connect({
				name : "deliciousBookmark"
			});
	var description = document.getSelection()
			? '' + document.getSelection()
			: '';

	responsePort.postMessage({
				action : "saveBookmark",
				selection : description,
				url : document.location.href,
				title : document.title
			});
}

// Also listen for new channels from the extension for when the button is
// pressed.
chrome.extension.onConnect.addListener(function(port) {
			console.log("Port name", port.name);
			console.assert(port.name === "deliciousBookmark");

			port.onMessage.addListener(function(msg) {
						console.log(["Received message", msg]);
						if (msg.action === 'getSelection') {
							sendBookmark();
						} else if (msg.action === 'getShortcutResponse') {
							console.log(["Shortcut to bind: ", msg.shortcut]);
							$(document).bind("keydown", msg.shortcut,
									sendBookmark);
						}
					});

		});

// get configured shortcut.
chrome.extension.sendRequest({
			action : "init"
		}, function(response) {
			console.log(["Init Response", response])
		});

new (function() {
	console.log("Trying to get configured shortcut");

	var port = chrome.extension.connect({
				name : "deliciousBookmark"
			});

	port.postMessage({
				action : "getShortcutRequest"
			});
})();